package com.yz.minded.aspect;

import com.yz.minded.common.BaseResponse;
import com.yz.minded.common.ErrorCode;
import com.yz.minded.common.ResultUtils;
import com.yz.minded.exception.BusinessException;
import com.yz.minded.pojo.FollowRelationship;
import com.yz.minded.pojo.User;
import com.yz.minded.service.FollowRelationshipService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 新用户注册时，管理员自动关注新注册用户
 * @author yz
 */
@Aspect
@Component
public class RegisterUserAspect {

    public static User user = null;

    @Resource
    private FollowRelationshipService followRelationshipService;

    @Around("execution(* com.yz.minded.controller.UserController.userRegister(..))")
    public Object setDefaultFans(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();
        // 检查返回值是否是 BaseResponse 类型
        long userId = 0;
        if (result instanceof BaseResponse<?> baseResponse) {
            userId = (long) baseResponse.getData(); // 获取 data 字段中的数据
        }
        FollowRelationship followRelationship = new FollowRelationship();
        followRelationship.setFollowerId(1L);
        followRelationship.setFollowedId(userId);
        boolean save = followRelationshipService.save(followRelationship);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"管理员默认关注失败");
        }
        // 返回给前端
        return ResultUtils.success(userId);
    }
}
